import { createRouter,createWebHashHistory } from "vue-router";
import {CookieUtil} from "@/utils/cookie";
import LoginPage from "@/view/LoginPage.vue";
import List from "@/view/List.vue";
import Layout from '@/layout/view.vue'

const routes = [
    {
        path: "/login",
        name: "Login",
        component: LoginPage,
    },
    {
        path: "/",
        component: Layout,
        name: "Layout",
        meta: {
            auth: true,
        },
        children: [
            {
                path: '',
                redirect: 'list'
            },
            {
                path: "/list",
                component: List,
            }
        ]
    }
]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    if (!CookieUtil.getCookie("token") && to.meta.auth) {
        // 非登录状态下进入需要登录的页面重定向到登录页面
        next({ name: "Login" });
    } else if (
        CookieUtil.getCookie("token") &&
        ["Login", "Register"].includes(to.name)
    ) {
        next("Layout");
    } else {
        next();
    }
});

export default router;
